# api/history_routes.py
from flask import Blueprint, request, jsonify
from math import ceil
import json
import os
from utils.logger import get_logger
from database import TaskDAO

logger = get_logger(__name__)

def create_history_routes(task_dao: TaskDAO):
    """创建历史记录相关路由"""

    history_bp = Blueprint('history', __name__)

    @history_bp.route('/history', methods=['GET'])
    def get_history():
        """获取处理历史"""
        try:
            page = int(request.args.get('page', 1))
            page_size = int(request.args.get('pageSize', 10))
            search = request.args.get('search', '')
            status = request.args.get('status', '')
            start_date = request.args.get('startDate', '')
            end_date = request.args.get('endDate', '')

            result = task_dao.get_task_history(
                page=page, page_size=page_size, search=search,
                status=status, start_date=start_date, end_date=end_date
            )

            items = []
            for task in result['tasks']:
                # 构建预览URL
                preview_url = None
                if task['preview_path'] and os.path.exists(task['preview_path']):
                    preview_url = f"/api/task-preview/{task['task_id']}"

                items.append({
                    'task_id': task['task_id'],
                    'human_name': task['human_name'],
                    'background_name': task['background_name'],
                    'output_name': task['output_name'],
                    'status': task['status'],
                    'trained': bool(task.get('trained', False)),
                    'progress': task['progress'],
                    'created_time': task['created_time'],
                    'completed_time': task['completed_time'],
                    'processing_time': task['processing_time_seconds'],
                    'preview_url': preview_url,
                    'result_path': task['result_path'],
                    'result_url': f"/api/download/{os.path.basename(task['result_path'])}" if task['result_path'] else None,
                    'result_available': bool(task['result_path'] and os.path.exists(task['result_path'])),
                    'parameters': json.loads(task['parameters']) if task['parameters'] else {},
                    'error_message': task['error_message']
                })

            return jsonify({
                'success': True,
                'items': items,
                'total': result['total'],
                'page': result['page'],
                'pageSize': result['page_size'],
                'totalPages': ceil(result['total'] / result['page_size'])
            })

        except Exception as e:
            logger.error(f"获取历史失败: {e}")
            return jsonify({'success': False, 'message': '获取历史失败'})

    @history_bp.route('/history/<task_id>', methods=['DELETE'])
    def delete_history(task_id):
        """删除历史记录"""
        try:
            success = task_dao.delete_task(task_id)

            if success:
                return jsonify({'success': True, 'message': '删除成功'})
            else:
                return jsonify({'success': False, 'message': '删除失败'}), 500

        except Exception as e:
            logger.error(f"删除历史记录失败: {e}")
            return jsonify({'success': False, 'message': '删除失败'}), 500

    return history_bp